package com.jy.modules.cims.common.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmCreditDetailService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;

/**
 * @classname: TCMmCreditDetailController
 * @description: 定义  债权明细 控制层
 * @author:  zhiqiang
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmCreditDetail")
public class TCMmCreditDetailController extends CimsBaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmCreditDetailController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDetailService")
    private TCMmCreditDetailService service;
     
    @Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.ExportAndImport")
	private ExportAndImport<?> exportAndImportService;
    
    @Autowired
	@Qualifier("com.jy.modules.cims.deal.service.DealService")
	public DealService dealService;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQuery".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/creditManage/queryTCMmCreditDetail");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/creditManage/addTCMmCreditDetail");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditManage/updateTCMmCreditDetail");
        }else if("toBatchUpdate".equals(operate)){
        	String creditorStatus = this.getParameterString("creditorStatus");
        	model = this.getCreditorStatus(creditorStatus);
        	model.setViewName("cims/creditManage/batchUpdateTCMmCreditDetail");
        } else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditManage/viewTCMmCreditDetail");
        }else if("toAddCredit".equals(operate)){//跳转到债权交易新增债权页面
        	model.setViewName("cims/creditManage/addCreditDealDetail");
        }else if("toAddRedempCredit".equals(operate)){//跳转到债权交易新增债权页面
        	model.setViewName("cims/creditRedemption/addCreditDealDetail");
        }else if("toPlanRedeemQuery".equals(operate)){//跳转至计划赎回日期统计页面
        	model.setViewName("cims/planRedeem/queryTotalPlanRedeemCredit");
        }
        
        return model;
    }
    
    /**
     * @author zhiqiang
     * @description:查询分页列表
     * @date 2015-01-07 16:21:37
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmCreditDetail")
    @ResponseBody
    public DataMsg queryListTCMmCreditDetail(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	///String valueContractCode = request.getParameter("valueContractCode");
    	String valueCooperorgCode = request.getParameter("valueCooperorgCode");
    	if(valueCooperorgCode != null){
        	dto.setCooperorgCode(valueCooperorgCode);
    	}
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmCreditDetailDTO> list = service.searchTCMmCreditDetailByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    /**
     * 查询未来每日赎回债权量报表
     * @Title queryPlanRedeemTotalList
     * @Description TODO
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception 
     * DataMsg 
     * @author lizhiqiang
     * @date 2016-7-28-下午2:47:39
     * @update 
     * @throws
     */
    @RequestMapping(value = "/queryPlanRedeemTotalList")
    @ResponseBody
    public DataMsg queryPlanRedeemTotalList(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception{
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<TCMmCreditDetailDTO> list ;
		if(SimpleStringUtils.isNotBlank(dto.getCooperorgCode())&&dto.getPlanRedeemDate()!=null){
			dealService.updateCreditPlanRedeemValue(dto);//计算赎回日期的债权价值
			list = service.searchCreditPlanRedeemTotalByPaging(params.getSearchParams());
		}else{
			list = null;
		}
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    
    /**
     * @author zhoupeng
     * @description:导出债权明细
     * @date 2015-10-31 16:21:37
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/exportCreditDetail")
    @ResponseBody
    public void exportCreditDetail(HttpServletRequest request,HttpServletResponse response, CreditDetailDto dto, @ModelAttribute DataMsg dataMsg) throws Exception{
    	Date date = new Date();
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    	formatter.format(date);
		String dealDate = formatter.format(date);
		String fileName = "债权明细"+dealDate;
    
    	Map<String, Object> searchParams = new HashMap<String, Object>();
//    	dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WAY);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<CreditDetailDto> list = service.searchTCMmCreditDetailExport(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        //List<CreditDetailDto> list = service.searchCreditDetailByPaging(params.getSearchParams());
        //searchTCMmLoanDetailExport
        
    	ExportAndImport<CreditDetailDto> exportAndImport = new ExportAndImport<CreditDetailDto>();
    	String columnCode = CimsConstant.CREDIT_RESULT_EXPORT_CODE;
    	String columnName = CimsConstant.CREDIT_RESULT_EXPORT_NAME;
		HSSFWorkbook workbook;
		try {
			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
			write(workbook, fileName, response);
		} catch (IOException e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.LOADDETAIL_FORM_FAILED + ":债权明细导出结果" + e);
		}
    }
    
    
    /**
  	 * 页面输出
  	 * @author zhoupeng
  	 * @param workbook
  	 * @param fileName
  	 * @param response
  	 * @throws IOException
  	 */
  	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

  		try {
  			
  			response.setContentType("application/vnd.ms-excel");
  			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
  			response.setCharacterEncoding("UTF-8");
  			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
  			workbook.write(response.getOutputStream());
  			response.getOutputStream().flush();
  		} catch (Exception e) {
  			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
  		} finally {
  			response.getOutputStream().close();
  		}
  	}
    
    @RequestMapping(value = "/queryListTCMmCreditDetailName")
    @ResponseBody
    public List<TCMmCreditDetailDTO> queryListTCMmCreditDetailName(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmCreditDetailDTO> list = service.searchTCMmCreditDetailByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return list;
    }

    /**
     * @author zhiqiang
     * @description:新增
     * @date 2015-01-07 16:21:37
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmCreditDetail")
    @ResponseBody
    public DataMsg insertTCMmCreditDetail(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmCreditDetailDTO)super.initDto(dto);

            service.insertTCMmCreditDetail(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:编辑
     * @date 2015-01-07 16:21:37
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmCreditDetail")
    @ResponseBody
    public DataMsg updateTCMmCreditDetail(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmCreditDetailDTO)super.initDto(dto);
           
            service.updateTCMmCreditDetail(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:删除
     * @date 2015-01-07 16:21:37
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmCreditDetail")
    @ResponseBody
    public DataMsg deleteTCMmCreditDetail(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 service.deleteTCMmCreditDetailByPrimaryKey(dto,ids);
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);

		}
        
        return dataMsg;
    }
    /**
     * @author zhiqiang
     * @description:通过主键查询 其明细信息
     * @date 2015-01-07 16:21:37
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmCreditDetailDTO dto = service.queryTCMmCreditDetailByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	e.printStackTrace();
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    
    /**
     * @author zhuwenbin
     * @description:想批量修改页面返回债权状态
     * @date 2015-02-04 16:21:37
     * @param id
     * @return
     */
    private ModelAndView getCreditorStatus(String creditorStatus) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmCreditDetailDTO dto = new TCMmCreditDetailDTO();
        	dto.setCreditorStatus(creditorStatus);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行getCreditorStatus异常：",e);
        }
        return model;
    }
    
    
    /**
     * @author zhuwenbin
     * @description:修改债权状态
     * @date 2015-02-05 16:21:37
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmCreditDetailStatus")
    @ResponseBody
    public DataMsg updateTCMmCreditDetailStatus(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg){
    	dto.setModifyTime(new Timestamp(new Date().getTime()));
        try {
        	dto = (TCMmCreditDetailDTO)super.initDto(dto);
           
            service.updateTCMmCreditDetailStatus(dto);
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	e.printStackTrace();
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateTCMmCreditDetailStatus异常：", e);
        }
        return dataMsg;
    }
    
    /**
     * @author zhuwenbin
     * @description:批量更新债权状态
     * @date 2015-02-05 16:21:37
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/batchupdateTCMmCreditDetail")
    @ResponseBody
    public DataMsg batchupdateTCMmCreditDetail(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
        try {
           
        	String creditorStatus = (String) this.getParameterString("creditorStatus");
        	String batch_ids = (String) this.getParameterString("batch_ids");
        	service.batchUpdateTCMmCreditStatus(batch_ids, creditorStatus);
        
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("批量修改成功");
            dataMsg.setData(this.makeJSONData(batch_ids));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法batchupdateTCMmCreditDetail异常：", e);
        }
        return dataMsg;
    }
    
    
    /**
     * @author zhoupeng
     * @description:更新债权信息
     * @date 2016-06-14 16:21:37
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/toBatchUpdateCredit")
    @ResponseBody
    public DataMsg toBatchUpdateCredit(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
        try {
           
        	String creditCode = (String) this.getParameterString("creditCode");
        	String creditSource = (String) this.getParameterString("creditSource");
        	//String batch_ids = (String) this.getParameterString("batch_ids");
        	//String mesg=creditDetailservice.updateCredit(creditCode,creditSource);
        
            dataMsg = super.initDataMsg(dataMsg);
           // dataMsg.setMsg(mesg);
            dataMsg.setStatus("ok");
        }catch (Exception e) {
        	String errorInfo = ExceptionUtils.getStackTraceAsString(e);
			e.printStackTrace();
        	dataMsg.setStatus("erro");
         	dataMsg.setMsg("实时刷新债权信息失败！\n<br>"+errorInfo);
            logger.error("执行方法toBatchUpdateCredit异常：", errorInfo);
        }
        return dataMsg;
    }
    
    
    
    /**
     * @author zhuwenbin
     * @description:查询分页列表
     * @date 2015-03-05 16:21:37
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListCreditDetail")
    @ResponseBody
    public DataMsg queryListCreditDetail(HttpServletRequest request, CreditDetailDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
//    	dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WAY);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<CreditDetailDto> list = service.searchCreditDetailByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    
	/**
	 * 导入Excel文件
	 * 
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/importCreditForPlanRedeemDate", method = RequestMethod.POST)
	public void importCreditForPlanRedeemDate(HttpServletResponse response, HttpServletRequest request, @ModelAttribute DataMsg dataMsg) throws Exception {
		Writer out = response.getWriter();
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			
			// 获取文件流
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			FileItem fileItems = file.getFileItem();
			String fileName = fileItems.getName();
			InputStream inputStream = file.getInputStream();

			Class<?> classObject = CreditDetailDto.class;
			// 设置需要进行数据转换的格式,map中的KEY值为fieldName
			Map<String, Map> excelColumnsConvertMap = new HashMap<String, Map>();
			String BillCode = CimsConstant.CREDIT_PLANREDEEMDATE_CODE;
		    String BillName = CimsConstant.CREDIT_PLANREDEEMDATE_NAME;
		    String Billimport = CimsConstant.CREDIT_PLANREDEEMDATE_ISIMPORT;
		    
		    
			List<CreditDetailDto> creditDealList = (List<CreditDetailDto>) exportAndImportService.excelImportParameter(inputStream, fileName,Billimport, BillCode,
					BillName, classObject, excelColumnsConvertMap);

			
			//更新计划赎回日期
	        dealService.updateCreditPlanRedeemDate(creditDealList);
			
			// 7.回显数据
			result.put("status", "ok");
			out.write(JSON.toJSONString(result));
		} catch (Exception e) {
			e.printStackTrace();
			dataMsg.failed(e.getMessage());
			result.put("status", "error");
			result.put("errorMassage", e.getMessage());
			out.write(JSON.toJSONString(result));
		}
	}
	
	/**
	 * 
	 * @throws Exception 
	 * @Description 导出
	 * ModelAndView  
	 * @date 2015-11-5
	 */
	@RequestMapping(value = "/exportExcelPlanRedeemTotalList")
    public void exportExcelPlanRedeemTotalList(HttpServletRequest request, TCMmCreditDetailDTO dto, HttpServletResponse response,@ModelAttribute DataMsg dataMsg) throws Exception{
	    	Map<String, Object> searchParams = new HashMap<String, Object>();
	    	searchParams.put("dto", dto);
	        QueryReqBean params = new QueryReqBean();
	        params.setSearchParams(searchParams);
	        List<TCMmCreditDetailDTO> list  = service.searchCreditPlanRedeemTotal(params.getSearchParams());
	        
	        Date date = new Date();
	    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
	    	formatter.format(date);
			String dealDate = formatter.format(date);
			String fileName = "赎回债权量"+dealDate;
			
			ExportAndImport<TCMmCreditDetailDTO> exportAndImport = new ExportAndImport<TCMmCreditDetailDTO>();
	    	String columnCode = CimsConstant.CREDIT_PLAN_REDEEM_VALUE_CODE;
	    	String columnName = CimsConstant.CREDIT_PLAN_REDEEM_VALUE_NAME;
			HSSFWorkbook workbook;
			try {
				workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
				write(workbook, fileName, response);
			} catch (IOException e) {
				dataMsg.failed(e.getMessage());
				throw new SysAssistException("导出未来每日赎回债权量失败" + e);
			}
    }
	
	
}
